package org.jeecg.modules.fund.job;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ExecutorBuilder;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.fund.entity.FundLibrary;
import org.jeecg.modules.fund.service.IFundLibraryService;
import org.jeecg.modules.fund.util.FundDetailHtmlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 获取基金详情
 */
@Slf4j
@Component
public class FundDetailJob {
    @Autowired
    private IFundLibraryService fundLibraryService;

    /**
     * 每周一至五，23点执行一次，代码刷新任务
     *
     * @throws InterruptedException
     */
    @Scheduled(cron = "0 0 3 * * MON-FRI")
    public void execute() throws InterruptedException {
        // 获取所有的基金
        log.info("任务开始时间：" + DateUtil.now());
        List<FundLibrary> list = fundLibraryService.list();
        try {
//            ExecutorService executorService = ExecutorBuilder
//                    .create()
//                    .setCorePoolSize(1)
//                    .setMaxPoolSize(1)
//                    .setKeepAliveTime(0)
//                    .build();
            AtomicInteger ti = new AtomicInteger();
            int size = list.size();
            for (int i = 0; i < size; i += 10) {
                int end = Math.min(i + 10, size);
                List<FundLibrary> subList = list.subList(i, end);
                for (FundLibrary fundLibrary : subList) {
                    log.info("次数：" + (ti));
                    JSONObject data = FundDetailHtmlUtil.getDetail(fundLibrary.getCode());
                    // 设置数据
                    fundLibrary
                            // 基金经理
                            .setManager(data.getStr("jjjl"))
                            // 管理公司
                            .setManagerCompany(data.getStr("glr"))
                            // 成立日期
                            .setBuildDate(data.getDate("clr"))
                            // 风险等级
                            .setRisk(data.getStr("fx"));
                    // fundLibraryService.updateById(fundLibrary);
                }
                fundLibraryService.updateBatchById(subList);
            }

            log.info("任务结束时间：" + DateUtil.now());
            //executorService.shutdown();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
